package com.bwie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.bwie.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2025/7/29 11:32
 */

// java example
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private String getCurrentUserName() {
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (token != null) {
            // 解析token获取用户名
            return TokenUtil.getUserName(token);
        }
        return "system";
    }


    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        String userName = getCurrentUserName();
        log.info("当前用户为：" + userName);
        this.strictInsertFill(metaObject, "createBy", String.class, userName);
        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        String userName = getCurrentUserName();
        log.info("当前用户为：" + userName);
        this.strictInsertFill(metaObject, "updateBy", String.class, userName);
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
    }
}
